package biz.datalk.industrialland.common.component.i18n;

import biz.datalk.industrialland.common.def.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * 国际化配置 LocaleResolver
 *
 * @author tarofang@163.com
 * @date 2019-08-14
 */
@Slf4j
public class DatalkLocaleResolver extends SessionLocaleResolver {

    /**
     * 先从 header 中获取
     * 如果 header 中未获取到 在从 session 中获取
     *
     * @author       tarofang@163.com
     * @date         2019-08-14
     *
     * @param request {@link HttpServletRequest}
     *
     * @return {@link LocaleContext}
     */
    @Override
    public LocaleContext resolveLocaleContext(HttpServletRequest request) {
        LocaleContext localeContext = getLocalContentFromRequestHeader(request);
        if (localeContext != null) {
            return localeContext;
        }

        // 从 session 中获取
        return getLocalContentFromSession(request);
    }

    private LocaleContext getLocalContentFromRequestHeader(HttpServletRequest request) {
        // STEP Number 声明相关变量
        Locale locale = null;

        // STEP Number 尝试从自定义的头中获取Header文本
        String localeText = StringUtils.trimWhitespace(request.getHeader(CommonConstant.I18N_PARAM));
        if (!(StringUtils.isEmpty(localeText))) {
            try {
                locale = StringUtils.parseLocale(localeText);

            } catch (Exception e) {
                log.warn("解析请求头[" + CommonConstant.I18N_PARAM + "]出错", e);

            }

        }

        // STEP Number 如果自定义头不存在，则直接从Accept-Language头中获取标准的Locale（获取权重最高的一个）
        if (locale == null) {
            locale = request.getLocale();

        }

        // STEP Number 校验获取结果，封装为{@link org.springframework.context.i18n.LocaleContext}返回
        if (locale != null) {
            Locale finalLocale = locale;
            return () -> finalLocale;

        }

        // STEP Number 其他情况下返回null
        return null;

    }

    private LocaleContext getLocalContentFromSession(HttpServletRequest request) {
        return super.resolveLocaleContext(request);
    }

    @Override
    public void setLocaleContext(HttpServletRequest request, HttpServletResponse response, LocaleContext localeContext) {
        super.setLocaleContext(request, response, localeContext);
    }
}
